"use client"
import { useState } from 'react';
import Link from 'next/link'
import useSWR from 'swr';

export default function HotArticlesPage() {
  const [page, setPage] = useState(1);
  const [pageSize] = useState(10);
  
  // 定义fetcher函数
  const fetcher = async (url: string) => {
    const response = await fetch(url, {
      method: 'GET',
      headers: {
        'Content-Type': 'application/json',
      },
    });
    
    if (!response.ok) {
      throw new Error(`HTTP error! status: ${response.status}`);
    }
    
    return response.json();
  };
  
  // 使用相对路径而不是绝对路径
  const { data, error, isLoading } = useSWR(
    `/api/articles?page=${page}&pageSize=${pageSize}`,
    fetcher
  );
  
  const articles = data?.data || [];

  const totalPages = data ? Math.ceil(data.total / pageSize) : 0;
  
  const updatePage = (key: string) => {
    if (key === 'pre') {
      setPage(page => Math.min(1, page - 1));
    } else if (key === 'next') {
      setPage(page => page + 1);
    }
  };

  return (
    <div className="container mx-auto px-4 py-8">
      <div className="flex justify-between items-center mb-4">
        <h3 className="text-1xl font-bold">
         <Link href={`/wp/add-hot`}>热门文章</Link> 
        </h3>
        <Link 
          href="/wp/hot-list" 
          className="text-sm text-blue-600 hover:text-blue-800"
        >
          管理热门文章 →
        </Link>
      </div>
      {isLoading&&
       <div className="container mx-auto px-4 py-8">加载中...</div>
      }
      {error&&
       <div className="container mx-auto px-4 py-8">加载失败: {error.message}</div>
      }
      {(!isLoading&&!articles.length)&&
       <div className="container mx-auto px-4 py-8">暂无数据</div>
      }
      {articles.length>0&&
      <div>
        <div className=" gap-6">
          {articles.map((article) => (
            <div key={article.id} className="rounded-lg p-4 hover:shadow-md transition-shadow">
              <Link href={`/wp/article?id=${article.id}`}>
                <h4 className="font-semibold mb-2">{article.title}</h4>
                {/* <p className="text-gray-600 mb-4">{article.summary || '暂无摘要'}</p> */ }
                <div className="mt-3">
                  {article.tags && article.tags.split(',').map((tag: string) => (
                    <span key={tag} className="inline-block bg-gray-200 rounded-full px-3 py-1 text-sm font-semibold text-gray-700 mr-2">
                      {tag}
                    </span>
                  ))}
                </div>
              </Link>
            </div>
          ))}
        </div>

        {/* 分页控件 */ }
        <div className="flex justify-center mt-8 space-x-2">
          <button 
            onClick={() => updatePage('pre')}
            disabled={page === 1}
            className="px-4 py-2 border rounded disabled:opacity-50"
          >
            ⬅
          </button>
          
          <span className="px-4 py-2">
            {page} / {totalPages} 
          </span>
          
          <button 
            onClick={() => updatePage('next')}
            disabled={page >= totalPages}
            className="px-4 py-2 border rounded disabled:opacity-50"
          >
            ➡
          </button>
        </div>
      </div>
    }
    </div>
  );
}